﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.IO;
using WPViThanhNien.Supports.Global;
using WPViThanhNien.Supports.Adapters;
using HtmlAgilityPack;

namespace WPViThanhNien.Supports.Factories
{
    public class DataFactory
    {
        // current type is editing
        static string creatingData = DataTypes.NONE;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataType"></param>
        public static void GetDataFromInternet(string dataType) 
        {
            lock (creatingData)
            {
                creatingData = dataType;
                if (creatingData == DataTypes.NONE)
                {
                    return;
                }
                StartServer(creatingData);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        public static void StartServer(string url) 
        {
            var request = WebRequest.Create(url);
            request.BeginGetResponse(new AsyncCallback(GetReponseCallback), request);
        }

        /// <summary>
        /// call back function after completed request
        /// </summary>
        /// <param name="result"></param>
        public static void GetReponseCallback(IAsyncResult result)
        {
            var request = (HttpWebRequest)result.AsyncState;
            var reponse = request.EndGetResponse(result);
            StreamReader reader = new StreamReader(reponse.GetResponseStream());
            var content = reader.ReadToEnd();
            var document = new HtmlDocument();

            switch (creatingData)
            {
                case (DataTypes.KHOA_HOC): GlobalDatas.ListKhoaHoc = DataAdapter.GetCatalogDataFromDocument(document);
                    break;
                case (DataTypes.VIEC_LAM): GlobalDatas.ListViecLam = DataAdapter.GetCatalogDataFromDocument(document);
                    break;
                case (DataTypes.TIN_MOI): GlobalDatas.ListTinMoi = DataAdapter.GetNewDataFromDocument(document);
                    break;
            }
        }
    }
}
